package kata21;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

public class DoubleLinkedList<E> implements ISimpleList<E> {

    private DoubleNode<E> node;

    @Override
    public void add(E e) {
        if(node == null){
            node = new DoubleNode(e,null);
        }else {
            DoubleNode currentNode = node;
            while (currentNode.next != null){
                currentNode = currentNode.next;
            }
            currentNode.setNext(new DoubleNode(e,currentNode));
        }
    }

    @Override
    public E find(E e) {
        DoubleNode next = node;
        while (next != null){
            if(e.equals(next.getValue())){
                return (E)next.getValue();
            }
            next = next.getNext();
        }
        return null;
    }

    @Override
    public void delete(E e) {
        DoubleNode currentNode = node;
        //第一个相等
        if(e.equals(currentNode.getValue())){
            node =  node.next;
            //下一个节点不为空,赋值上一个节点为空
            if(node != null){
                node.setPre(null);
            }
        }else {
            while (currentNode != null){
                //第一个
                if(e.equals(currentNode.getValue())){
                    //当前节点的上一节点 -> next = 当前节点的下一节点 (即把当前节点置 null)
                    if(currentNode.getPre() != null){
                        currentNode.getPre().setNext(currentNode.getNext());
                    }
                    //当前节点的下一节点 -> pre =  当前节点的上一节点
                    if(currentNode.getNext() != null){
                        currentNode.getNext().setPre(currentNode.getPre());
                    }
                    currentNode = null;
                    break;
                }
                //当前节点  <-  当前节点下一个节点
                currentNode = currentNode.getNext();
            }
        }
    }

    @Override
    public String values() {
        DoubleNode currentNode = node;
        List<Object> result = new ArrayList<>();
        while (currentNode != null){
            result.add(currentNode.getValue());
            currentNode = currentNode.next;
        }
        return result.toString();
    }

    @Data
    static class DoubleNode<T> {
        private DoubleNode<T> pre;
        private T value;
        private DoubleNode<T> next;

        public DoubleNode(T value,DoubleNode<T> pre){
            this.value = value;
            this.pre = pre;
        }
    }
}
